package model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-24
 * Time：11:56
 */
public class RemarkDao {
    public void insert(Remark remark) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.建立连接
            connection = DBUtil.getConnection();
            //2.构造SQL语句
            String sql = "insert into remark values(null, ?, ?, ?, now())";
            statement = connection.prepareStatement(sql);
            statement.setString(1, remark.getContent());
            statement.setInt(2, remark.getBlogId());
            statement.setInt(3, remark.getUserId());
            //3.执行sql
            int ret = statement.executeUpdate();
            if (ret == 1) {
                System.out.println("插入成功！");
            } else {
                System.out.println("插入失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }

    public List<Remark> selectById(int blogId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Remark> remarks = new ArrayList<>();
        try {
            //1.connect
            connection = DBUtil.getConnection();
            //2.construct sql
            String sql = "SELECT remark.*, user.username   FROM remark   JOIN user ON remark.userId = user.userId WHERE remark.blogId = ? order by remarkTime desc";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, blogId);
            //3.execute sql
            resultSet = statement.executeQuery();
            //4.traversal result
            while (resultSet.next()) {
                Remark remark = new Remark();
                remark.setBlogId(resultSet.getInt("blogId"));
                remark.setUserId(resultSet.getInt("userId"));
                //博客列表页，只需要正文的摘要就可以
                remark.setContent(resultSet.getString("content"));
                remark.setRemarkTime(resultSet.getDate("remarkTime"));
                remark.setUsername(resultSet.getString("username"));
                remarks.add(remark);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return remarks;
    }
}
